//
//  DisplayDocument.m
//  OASystem
//
//  Created by mac on 14-5-7.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "DisplayDocument.h"

@interface DisplayDocument ()

@end

@implementation DisplayDocument
@synthesize sendTimeStr,ouCertGuidStr,sysGuidStr,fileTypeStr;
@synthesize displayHandleDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        if(!displayHandleDic)
            displayHandleDic = [[NSDictionary alloc] init];
    }
    return self;
}

//返回上一级
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initNavi
{
    //初始化UINavigation
    self.navigationItem.titleView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 100, 44)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.text = @"待收公文";
    titleLabel.font = HEIGHT_FONT(18.0f);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    [self.navigationItem.titleView addSubview:titleLabel];
    
    //添加导航又边用户信息
    //初始化UINavigation左按钮
    UIButton *helloButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 80, 24)];
    [helloButton setTitle:[NSString stringWithFormat:@"你好，%@",USER_NICK_NAME] forState:UIControlStateNormal];
    helloButton.titleLabel.font = HEIGHT_FONT(13.0f);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:helloButton];
    
    //初始化UINavigation左按钮
    UIButton *naviButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 45, 24)];
    [naviButton setTitle:@"返回" forState:UIControlStateNormal];
    naviButton.titleLabel.font = HEIGHT_FONT(13.0f);
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_n.png"] forState:UIControlStateNormal];
    [naviButton setBackgroundImage:[UIImage imageNamed:@"title_back_bg_p.png"] forState:UIControlStateHighlighted];
    [naviButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:naviButton];
}

- (void)initView
{
//    if(displayHandleScr)
//        [displayHandleScr removeFromSuperview];
    
    int offY = 10;
    for (int i = 0; i < titleArray.count; i++)
    {
        CGSize size;
        NSString *str;
        if(0 <i && i<4)
            str = [[displayHandleDic objectForKey:[keyArray objectAtIndex:i]] objectAtIndex:0];
        else
            str = [displayHandleDic objectForKey:[keyArray objectAtIndex:i]];
        if(str.length != 0)
        {
            size=[HWLabelTextSize getSuitSizeWithString:str fontSize:14 bold:YES sizeOfX:210];
            if(size.height<=16.702000)
                size= CGSizeMake(210, 40);
            else
                size= CGSizeMake(210, 20+size.height/16.702000*20);
        }
        else
            size= CGSizeMake(210, 40);
        
        UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, offY, 210, size.height)];
        contentLabel.text = str;
        
        if(size.height > 40)
            contentLabel.numberOfLines = 2;//(int)(size.height-20)/20;
        
        
        contentLabel.font = HEIGHT_FONT(14.0f);//[UIFont fontWithName:@"Arial" size:14.0f];
        contentLabel.backgroundColor = (i >= titleArray.count -2)?[UIColor clearColor]:[UIColor whiteColor];
        [displayHandleScr addSubview:contentLabel];
        
        
        if(i >= titleArray.count -2)
        {
            NSLog(@"iiiuuu-----%@",[titleArray objectAtIndex:i]);
            NSLog(@"str-----%@",str);

            if(str.length != 0)
            {
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getAttack)];
                contentLabel.userInteractionEnabled = YES;
                [contentLabel addGestureRecognizer:tap];
            }
        }
        
        if(0<i && i<4)
        {
            contentLabel.userInteractionEnabled = YES;
            
            contentLabel.tag = i;
            
            UIButton *selectTip = [UIButton buttonWithType:UIButtonTypeCustom];
            selectTip.frame = CGRectMake(170, 0, 40, 40);
            selectTip.tag = i;
            [selectTip addTarget:self action:@selector(slectTipAction:) forControlEvents:UIControlEventTouchUpInside];
            [selectTip setBackgroundImage:[UIImage imageNamed:@"scetel.png"] forState:UIControlStateNormal];
            [contentLabel addSubview:selectTip];
        }
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, offY, 90, size.height)];
        label.text = [titleArray objectAtIndex:i];
        label.font = HEIGHT_FONT(14.0f);
        label.textAlignment = NSTextAlignmentRight;
        [displayHandleScr addSubview:label];
        offY = offY+size.height+10;
    }
    displayHandleScr.contentSize = CGSizeMake(320, offY+ 120);
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(60, offY+5, 200, 40);
    [button setTitle:@"签收公文" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"but.png"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"but_hover.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(hanleAction) forControlEvents:UIControlEventTouchUpInside];
    [displayHandleScr addSubview:button];
}

- (void)slectTipAction:(UIButton *)button
{
    selectRow = button.tag;
    
    //选择意见
    if(selectTipBackView)
        [selectTipBackView removeFromSuperview];
    
    if(listArr)
        listArr = nil;
    NSString *keyStr = (selectRow==1?@"simidengji":selectRow==2?@"baomiqixian":@"jinjichengdu");
    listArr = [[NSArray alloc] initWithArray:[displayHandleDic objectForKey:keyStr]];
    
    selectTipBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    selectTipBackView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:selectTipBackView];
    
    
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    backImage.alpha = 0.5;
    backImage.backgroundColor = [UIColor blackColor];
    [selectTipBackView addSubview:backImage];
    
    unsigned long height = listArr.count*60;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(10, (self.view.frame.size.height-height-30)/2, 300, height+30)];
    [selectTipBackView addSubview:contentView];
    
//    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
//    title.text = @"请选择签收意见";
//    title.backgroundColor = [UIColor blackColor];
//    title.textColor = [UIColor whiteColor];
//    title.font = HEIGHT_FONT(16.0f);
//    [contentView addSubview:title];
    
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, 300, height) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    //    table.separatorStyle = UITableViewCellSelectionStyleNone;
    [contentView addSubview:table];
}


//获取链接
- (void)getAttack
{
    NSLog(@"url---->%@",[displayHandleDic objectForKey:@"url"]);
    
    NSString *attackUrl = [displayHandleDic objectForKey:@"url"];
    
    if([attackUrl hasPrefix:@"/"]||[attackUrl hasPrefix:@" /"])
        attackUrl = [NSString stringWithFormat:@"%@%@",base_url,attackUrl];
    else
        attackUrl = [NSString stringWithFormat:@"%@/%@",base_url,attackUrl];
    
    attackUrl = [attackUrl  stringByReplacingOccurrencesOfString:@" " withString:@""];
    attackUrl = [attackUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(![[UIApplication sharedApplication] openURL:[NSURL URLWithString:attackUrl]])
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"获取附件失败"}];
}

//处理请求
- (void)hanleAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LOAD" object:nil];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *param = [displayHandleDic objectForKey:@"jpdFileType"];
        param = (param.length ==0?@"":param);
        
        NSLog(@"%@",TEMP_USERNAME);
        NSLog(@"sendTimeStr--%@",sendTimeStr);
        NSLog(@"sysGuidStr--%@",sysGuidStr);
        NSLog(@"ouCertGuidStr--%@",ouCertGuidStr);
        NSLog(@"simidengjiStr--%@",simidengjiStr);
        NSLog(@"baomiqixianStr--%@",baomiqixianStr);
        NSLog(@"jinjichengduStr--%@",jinjichengduStr);
        NSLog(@"jpdFileType--%@",param);
        
        NSDictionary *dic = [[SendHttpOperation shareSendHttpOperation] Archive_Sign:TEMP_USERNAME
                                                                            sendTime:sendTimeStr
                                                                             SysGuid:sysGuidStr
                                                                            FileType:@"25"
                                                                          OuCertGuid:ouCertGuidStr
                                                                         jpdFileType:param
                                                                             jpdMiji:simidengjiStr
                                                                          jpdBaoMiQx:baomiqixianStr
                                                                            jpdJinji:jinjichengduStr];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"REMOVE" object:nil];
            if ([[dic objectForKey:@"errcode"] intValue] == 0)
            {
                //push到展示界面
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"签收成功"}];
                
                NSArray *array = [self.navigationController viewControllers];
                [self.navigationController popToViewController:array[3] animated:YES];
            }
            else if([[dic objectForKey:@"errcode"] intValue] == 1||[[dic objectForKey:@"errcode"] intValue] == 2)
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":([[dic objectForKey:@"errcode"]intValue]==1?@"获取数据失败":@"用户身份验证失败")}];
            else
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TIP" object:@{@"msg":@"服务器异常，请稍候重试"}];
        });
    });
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = NOTICEBOARD_BACKCOLOR;
    
    [self initNavi];
    
    if(!titleArray)
        titleArray = [[NSArray alloc] initWithObjects:@"发文号：",@"私密等级：",@"保密期限：",@"紧急程度：",@"主送机关：",@"抄送机关：",@"主办机关：",@"协办机关：",@"主题词：",@"公文标题：",@"发文部门：",@"收文部门：",@"公文备注：",@"发文时间：",@"印发份数：",@"公文正文：",@"公文附件：", nil];
    if(!keyArray)
        keyArray = [[NSArray alloc] initWithObjects:@"fawenhao",@"simidengji",@"baomiqixian",@"jinjichengdu",@"zhusongjiguan",@"chaosongjiguan",@"zhubanjiguan",@"xiebanjiguan",@"zhutici",@"gongwenbiaoti",@"fawenbumen",@"shouwenbumen",@"gongwenbeizhu",@"fawenshijian",@"yinfafenshu",@"gongwenzhengwen",@"gongwenfujian", nil];
    
    simidengjiStr = [[displayHandleDic objectForKey:@"simidengji"] objectAtIndex:0];
    baomiqixianStr = [[displayHandleDic objectForKey:@"baomiqixian"] objectAtIndex:0];
    jinjichengduStr = [[displayHandleDic objectForKey:@"jinjichengdu"] objectAtIndex:0];
    
    [self initView];
}


#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews)
    {
        [subview removeFromSuperview];
    }
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 25)];
    tipLabel.text = [listArr objectAtIndex:indexPath.row];
    tipLabel.font = HEIGHT_FONT(16.0f);
    [cell.contentView addSubview:tipLabel];
    
    
    UIImageView *slectImage = [[UIImageView alloc] initWithFrame:CGRectMake(265, 18, 24, 24)];
    [cell.contentView addSubview:slectImage];
    
    NSString *str = selectRow==1?simidengjiStr:selectRow==2?baomiqixianStr:jinjichengduStr;
    if([str isEqualToString:[listArr objectAtIndex:indexPath.row]])
        slectImage.image = [UIImage imageNamed:@"contact_checkbox_c.png"];
    else
        slectImage.image = [UIImage imageNamed:@"contact_checkbox_n.png"];
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(selectRow == 1)
        simidengjiStr = [listArr objectAtIndex:indexPath.row];
    else if(selectRow == 2)
        baomiqixianStr = [listArr objectAtIndex:indexPath.row];
    else
        jinjichengduStr = [listArr objectAtIndex:indexPath.row];
    [table reloadData];
    
    if(selectTipBackView)
        [selectTipBackView removeFromSuperview];
    
    NSArray *arr = [[NSArray alloc] initWithArray:displayHandleScr.subviews];
    
    for (UILabel *label in arr)
    {
        if(label.tag == selectRow)
            label.text = [listArr objectAtIndex:indexPath.row];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
